<template>
  <div class="div-user-sum">
    <div class="div-top">
      <el-button type="primary" style="margin:0 0 10px 10px" @click="back"
        >返回</el-button
      >
    </div>

    <el-dialog :visible.sync="dialogVisible" title="编辑组件">
      <el-form :model="editForm" :rules="rules" ref="editForm">
        <el-form-item label="封面" prop="componentCover">
          <div class="avataruploads">
            <div
              class="avatarupcover avatarupcover-add"
              @click="$refs.icon_add.click()"
            >
              <i class="el-icon-plus"></i>
            </div>
            <img
              :src="baseurl + editForm.componentCover"
              v-if="editForm.componentCover"
            />
            <input
              ref="icon_add"
              type="file"
              accept=".jpg, .png, .JPG, .PNG"
              style="display: none"
              @change="iconAdd($event)"
            />
          </div>
        </el-form-item>
        <el-form-item label="组件标识">
          <el-input v-model="editForm.componentSign" disabled></el-input>
        </el-form-item>
        <el-form-item label="组件名称" prop="componentName">
          <el-input v-model="editForm.componentName"></el-input>
        </el-form-item>
        <el-form-item label="组件介绍" prop="componentInfo">
          <el-col :span="24">
            <editor-more
              :content="editForm.componentInfo"
              @change="introductionAddChange"
            ></editor-more>
          </el-col>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveEdit">保存</el-button>
      </div>
    </el-dialog>

    <div style="margin: 10px;">
      <el-table :data="tableDate" border>
        <el-table-column
          prop="componentCover"
          label="封面"
          width="140px"
          align="center"
        >
          <template slot-scope="scope">
            <el-image
              :src="baseurl + scope.row.componentCover"
              class="cover-content"
              fit="cover"
            >
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline"></i>
              </div>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column
          prop="componentSign"
          label="组件标识"
          align="center"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="componentName"
          label="组件名称"
          align="center"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="componentInfo"
          label="组件介绍"
          align="center"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column label="操作" align="center" width="350">
          <template slot-scope="scope">
            <el-button type="primary" @click="openEdit(scope.row)" size="small"
              >编辑</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div style="margin: 10px; text-align: center;">
        <el-pagination
          background
          @size-change="sizeChange"
          @current-change="currentChange"
          :current-page="pageNum"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import { selectVrModelDetail, updateVrModelComponent } from '@/api/model.js'
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import { putProgress, createMultipartUpload, listObjects } from '@/utils/oss.js'
import EditorMore from '@/components/Editor/index.vue'
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {
    EditorMore
  },
  props: {
    vrModelId: {
      type: Number
    }
  },

  data() {
    //这里存放数据
    return {
      tableDate: [],
      pageNum: 1,
      pageSize: 10,
      total: 10,
      glbdetails: {},
      dialogVisible: false,
      editForm: {
        componentSign: '',
        componentName: '',
        componentInfo: ''
      },
      rules: {
        componentName: [
          {
            required: true,
            message: '请输入组件名称',
            trigger: 'blur'
          }
        ],
        componentInfo: [
          {
            required: true,
            message: '请输入组件介绍',
            trigger: 'blur'
          }
        ],
        componentCover: [
          {
            required: true,
            message: '请上传组件封面',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  watch: {
    glbdetails: {
      immediate: true,
      deep: true,
      handler(newVal) {
        if (newVal.vrModelComponentDtoList) {
          this.total = newVal.vrModelComponentDtoList.length || 0
          this.updateTableData()
        }
      }
    }
  },
  methods: {
    currentChange(newPage) {
      this.pageNum = newPage
      this.updateTableData()
    },
    sizeChange(newSize) {
      this.pageSize = newSize
      this.updateTableData()
    },
    updateTableData() {
      const allData = this.glbdetails.vrModelComponentDtoList || []
      this.total = allData.length

      const maxPage = Math.ceil(this.total / this.pageSize)
      if (this.pageNum > maxPage) this.pageNum = Math.max(1, maxPage)

      const start = (this.pageNum - 1) * this.pageSize
      const end = start + this.pageSize
      this.tableDate = allData.slice(start, end)
    },
    openEdit(row) {
      this.editForm = { ...row }
      this.dialogVisible = true
    },
    saveEdit() {
      // const index = this.glbdetails.vrModelComponentDtoList.findIndex(
      //   item => item.componentSign === this.editForm.componentSign
      // )
      // if (index !== -1) {
      //   this.$set(this.glbdetails.vrModelComponentDtoList, index, {
      //     ...this.editForm
      //   })
      // }
      // this.$emit(
      //   'glbdetailsUpdate',
      //   JSON.parse(JSON.stringify(this.glbdetails))
      // )
      // this.dialogVisible = false

      // this.updateTableData()

      this.dataloading = true
      setTimeout(_ => {
        this.dataloading = false
      }, 1000)
      this.$refs.editForm.validate(valid => {
        if (valid) {
          var data = Object.assign({}, this.editForm)
          updateVrModelComponent(data).then(res => {
            if (res.code == '200') {
              this.$message({
                message: '编辑成功',
                type: 'success'
              })
              this.dialogVisible = false
              this.glbdetails = res.data // 修改为使用 item.vrModelComponentReqList
              this.getdetails()
            } else {
              this.$message({
                message: res.message,
                type: 'error'
              })
            }
          })
        }
      })
    },
    back() {
      this.$emit('back')
    },
    introductionAddChange(data) {
      this.editForm.componentInfo = data.html
    },
    iconAdd(event) {
      const files = event.target.files
      if (!files || files.length === 0) return

      const file = files[0]
      const key = `szhjxpt/vrResourceCover/${file.name}`
      putProgress(key, file).then(() => {
        this.editForm.componentCover = key
        this.$refs.icon_add.value = ''
      })
    },
    getdetails() {
      selectVrModelDetail({ vrModelId: this.vrModelId }).then(res => {
        if (res.code == '200') {
          this.$message({
            message: '查询成功',
            type: 'success'
          })

          this.glbdetails = res.data // 修改为使用 item.vrModelComponentReqList
        } else {
          this.$message({
            message: res.message,
            type: 'error'
          })
        }
      })
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getdetails()
  },
  //生命周期 - 挂载完成（可以访问DOM元素）

  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {} //如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style></style>
